package com.project.bookstore.config.security;

import com.project.bookstore.user.mapper.UserMapper;
import com.project.bookstore.user.pojo.UserDetailDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


@Slf4j
@Configuration
public class UserDetailServiceImpl implements UserDetailsService{
    @Autowired
    UserMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailDO userInDB = mapper.selectUserDetail(username);
        if (userInDB==null){
            log.debug("用户名不存在");
            throw new BadCredentialsException("=== 用户名不存在 ===");
        }
        UserDetails userDetails = User.builder()
                .username(userInDB.getUsername())
                .password(userInDB.getPassword())
                .authorities(userInDB.getPermissions().toArray(new String[]{}))
                .disabled(false)
                .accountExpired(false)
                .credentialsExpired(false)
                .accountLocked(false)
                .build();
        log.debug("userDetails:【{}】",userDetails);
        return userDetails;
    }
}

